package itsm.isperp.framework.security.authentication;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.utils.NetUtils;
import itsm.isperp.module.entity.app.AppLoginLog;
import itsm.isperp.module.service.app.AppLoginLogService;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2014-2-27
 * @since 1.0
 * 
 */
public class IsperpAuthenticationFailureHandler extends
		ExceptionMappingAuthenticationFailureHandler {

	@Override
	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException exception)
			throws IOException, ServletException {

		Throwable cause = exception.getCause();

		// 登录日志
		AppLoginLogService appLoginLogService = ContextHolder
				.getSpringBean("appLoginLogService");

		String name = request
				.getParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY);
		String msg = null;
		String ip = NetUtils.getIpAddr(request);

		if (exception instanceof SessionAuthenticationException) {

			msg = "登录用户数超出范围";
		} else if (cause instanceof BadCredentialsException) {

			msg = "登录失败";

		} else {
			msg = exception.toString();
		}

		AppLoginLog entity = new AppLoginLog();
		entity.setUsername(name);
		entity.setCreatedDate(new Timestamp(new Date().getTime()));
		entity.setInfo(msg);
		entity.setSuccess(false);
		entity.setIp(ip);
		appLoginLogService.saveOrUpdate(entity);

		super.onAuthenticationFailure(request, response, exception);

	}
}
